#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
#define rep(i, a, b) for (int i = (a); i <= (b); i++)
#define per(i, a, b) for (int i = (a); i >= (b); i--)
#define endl '\n'
const int N = 2e5 + 5;

mt19937 mt(chrono::steady_clock::now().time_since_epoch().count());
int n, m;
char s[N];
int f[N], g[N];
ll solve(char c) {
  f[0] = 0, g[n + 1] = 0;
  rep(i, 1, n) f[i] = f[i - 1] + (s[i] == c);
  per(i, n, 1) g[i] = g[i + 1] + (s[i] == c);
  ll sum = 0;
  rep(i, 1, n) {
    if (s[i] != c) sum += min(f[i], g[i]);
  }
  return sum;
}
void solve() {
  cin >> n;
  rep(i, 1, n) cin >> s[i];
  cout << min(solve('a'), solve('b')) << endl;
}
int main() {
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  int t;
  cin >> t;
  while (t--) solve();
  return 0;
}